import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/xian_huo_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/page/aMapView/amap_tool.dart';
import 'package:lcapp/page/search/xianhuo_item.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:lcapp/page/xianhuo/xianhuo_sx_address.dart';
import 'package:lcapp/page/xianhuo/xianhuo_sx_lx.dart';

class XianHuoPage extends StatefulWidget {
  const XianHuoPage({Key? key}) : super(key: key);

  @override
  _XianHuoPageState createState() => _XianHuoPageState();
}

class _XianHuoPageState extends State<XianHuoPage> {

  List<XianHuoDataEntity> xianHuos = [];
  int pageNum = 1;
  int pageSize = 10;

  int sort = 0;
  String address = '全国';
  List plList = [];
  String plStr = '';
  List lxList = [];
  String lxStr = '';
  List dwList = [];
  String dwStr = '';
  StreamSubscription? _streamSubscription;
  StreamSubscription? _locationSubscription;
  GlobalKey _globalKey = GlobalKey();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((callback)async {
      // AmapTool.startLocation(isShowToast: true);
    });
    _locationSubscription = eventBus.on<LocationState>().listen((event) {
      setState(() {
      });
    });
    _streamSubscription = eventBus.on<FabuState>().listen((event) {
      if (event.type == 0) {
        pageNum=1;
        getXianHuo();
      }
    });
    address = '全国';
    getXianHuo();
  }

  getXianHuo()async{
    List ids = [];
    for (var element in plList) {
      ids.add(element['id']);
    }
    Map<String,dynamic> data = {
      'page':pageNum,
      'size':pageSize,
      'sort':sort,
      'types':ids,
    };
    if(address!='全国'&&address!='附近'){
      data['address'] = address;
    }
    if(address=='全国'){
      sort = 0;
    }else if(address == '附近'){
      sort = 1;
      // data['myLatitude'] = AmapTool.locationEntity.latitude;
      // data['myLongitude'] = AmapTool.locationEntity.longitude;
    }else{
      sort = 2;
    }
    if(lxList.isNotEmpty){
      data['publishType'] = lxList[0]['id'];
    }
    if(dwList.isNotEmpty){
      data['productUnit'] = dwList[0]['id'];
    }
    ResponseData res = await HomeAPI.getXianHuos(data);
    if(res.code==200){
      if(pageNum==1){
        xianHuos.clear();
      }
      List arr = res.data??[];
      for (var element in arr) {
        XianHuoDataEntity entity = XianHuoDataEntity().fromJson(element);
        xianHuos.add(entity);
      }
    }
    if(mounted){setState(() {
    });}
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _streamSubscription?.cancel();
    _locationSubscription?.cancel();
  }


  @override
  Widget build(BuildContext context) {
    return NestedScrollView(
      headerSliverBuilder: (context,vale){
        return [
          SliverAppBar(
            leading: Container(),
            leadingWidth: 0,
            toolbarHeight: 0,
            backgroundColor:  defaultBarColor,
            pinned:true,
            primary: false,
            floating: true,
            bottom: PreferredSize(
              child: Container(
                height: 110.w,
                padding: EdgeInsets.only(left: 30.w,right: 30.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(35.w),topRight: Radius.circular(35.w))
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      child: Row(
                        children: [
                          GestureDetector(
                            onTap: (){
                              final RenderBox renderBox = _globalKey.currentContext?.findRenderObject()! as RenderBox;
                              Offset offset = renderBox.localToGlobal(Offset.zero);
                              SmartDialog.dismiss();
                              SmartDialog.show(
                                alignment: Alignment.center,
                                clickMaskDismiss: true,
                                maskColor: Colors.transparent, builder: (BuildContext context) {
                                  return XianHuoSXAddress(
                                    topSpace: renderBox.size.height+offset.dy,
                                    proIndex: sort,
                                    callBack: (map){
                                      setState(() {
                                        if(map!=null){
                                          address = map['name'];
                                          if(address=='全国货源'){
                                            sort = 0;
                                            address = '全国';
                                          }else if(address=='附近货源'){
                                            sort = 1;
                                            address = '附近';
                                          }else{
                                            sort = 2;
                                          }
                                        }else {
                                          address = '全国';
                                          sort = 0;
                                        }
                                        pageNum = 1;
                                        getXianHuo();
                                      });
                                    },);
                              },);
                            },
                            child: Container(
                              margin: EdgeInsets.only(right: 20.w),
                              child: Row(
                                children: [
                                  Image.asset("assets/xh/xh_dw.png",width: 20.w,),
                                  SizedBox(width: 10.w,),
                                  Text(address.length>5?address.substring(0,4)+'...':address,maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(
                                      color: Color(0xff1A051D),
                                      fontSize: 26.sp,
                                      fontWeight: FontWeight.w500
                                  ),),
                                ],
                              ),
                            ),
                          ),
                          sxItem(plList.isEmpty?'品类筛选':plStr,type: 0,icon: Icon(Icons.arrow_drop_down,color: plList.isEmpty?Color(0xff1A051D):defaultBarColor,size: 35.w,),color: plList.isEmpty?Color(0xff1A051D):defaultBarColor),
                          SizedBox(width: 20.w,),
                          sxItem(lxList.isEmpty?'类型筛选':lxStr,type: 1,icon: Icon(Icons.arrow_drop_down,color: lxList.isEmpty?Color(0xff1A051D):defaultBarColor,size: 35.w,),color: lxList.isEmpty?Color(0xff1A051D):defaultBarColor),

                        ],
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(color: Color(0xffeeeeee),width: 1),
                        borderRadius: BorderRadius.circular(100.w)
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 15.w,vertical: 15.w),
                    ),
                    sxItem(dwList.isEmpty?'单位换算':dwStr,type: 2,icon: Icon(Icons.cached_outlined,color: dwList.isEmpty?Color(0xff666666):defaultBarColor,size: 35.w,),color: dwList.isEmpty?Color(0xff1A051D):defaultBarColor),

                    // sxItem('筛选',type: 5,icon: Icon(Icons.arrow_drop_down,color: Color(0xff1A051D),size: 50.w,),color: Color(0xff1A051D)),
                  ],
                ),
              ),
              key: _globalKey,
              preferredSize: Size(1.sw,110.w),
            ),
            elevation: 0,
          ),
        ];
      },
      body: Container(
        color: Color(0xffeeeeee),
        child: EasyRefresh(
          header: myRefreshHeader(),
          footer: myRefreshFooter(),
          onRefresh: ()async{
            pageNum = 1;
            getXianHuo();
          },
          onLoad: ()async{
            pageNum++;
            getXianHuo();
          },
          child: AlignedGridView.count(
            padding: EdgeInsets.only(top: 20.w),
            itemCount: xianHuos.length,
            crossAxisCount: 2,
            crossAxisSpacing: 10.w,
            mainAxisSpacing: 10.w,
            itemBuilder: (context,index){
              return XianHuoItem(entity: xianHuos[index], chooseFun: (){},);
            },
          ),
        ),
      ),
    );
  }

  Widget sxItem(String name,{required Icon icon,required Color color,required int type}){

    return GestureDetector(
      onTap: (){
        final RenderBox renderBox = _globalKey.currentContext?.findRenderObject() as RenderBox;
        Offset offset = renderBox.localToGlobal(Offset.zero);
        List selectIds = [];
        if(type==0){
          for (var element in plList) {
            selectIds.add(element['id']);
          }
        }else if(type==1){
          for (var element in lxList) {
            selectIds.add(element['id']);
          }
        }
        if(type==2){
          SmartDialog.show(
            alignment: Alignment.center,
            clickMaskDismiss: true,
            maskColor: Colors.transparent, builder: (BuildContext context) {
              return Container(
                color: Colors.transparent,
                child: Column(
                  children: [
                    GestureDetector(
                      onTap: (){
                        SmartDialog.dismiss();
                      },
                      child: Container(
                        color: Colors.transparent,
                        height: offset.dy+renderBox.size.height,
                      ),
                    ),
                    Expanded(child: GestureDetector(
                      onTap: (){
                        SmartDialog.dismiss();
                      },
                      child: Container(
                        width: 1.sw,
                        color: Color.fromRGBO(0, 0, 0, 0.25),
                        child: GestureDetector(
                          onTap: (){},
                          child: Stack(
                            children: [
                              Positioned(
                                child: Container(
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(10.w)
                                  ),
                                  height: 280.w,
                                  width: 230.w,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                    children: [
                                      GestureDetector(
                                        onTap: (){
                                          SmartDialog.dismiss();
                                          pageNum=1;
                                          dwList = [];
                                          dwStr = '';
                                          for (var element in dwList) {
                                            dwStr += element['name'];
                                          }
                                          getXianHuo();
                                        },
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            SizedBox(width: 40.w,),
                                            Text('全部',style: TextStyle(
                                                color: dwList.isEmpty? Color(0xffEA6B2B):Colors.black,
                                                fontSize: 30.sp,
                                                fontWeight: FontWeight.w500
                                            ),),
                                            SizedBox(width: 10.w,),
                                            Icon(Icons.arrow_forward_ios,color: Colors.transparent,size: 30.sp,)
                                          ],
                                        ),
                                      ),
                                      GestureDetector(
                                          onTap: (){
                                            SmartDialog.dismiss();
                                            dwList = [{'name':'每斤/价格','id':'1'}];
                                            dwStr = '';
                                            for (var element in dwList) {
                                              dwStr += element['name'];
                                            }
                                            pageNum=1;
                                            getXianHuo();
                                          },
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              SizedBox(width: 40.w,),
                                              Text('每斤/价格',style: TextStyle(
                                                  color: dwStr=='每斤/价格'? Color(0xffEA6B2B):Colors.black,
                                                  fontSize: 30.sp,
                                                  fontWeight: FontWeight.w500
                                              ),),
                                              SizedBox(width: 10.w,),
                                              Icon(Icons.arrow_forward_ios,color: Colors.transparent,size: 30.sp,)
                                            ],
                                          )
                                      ),
                                      Container(width: 200.w,height: 1,color: Color(0xffeeeeee),),
                                      GestureDetector(
                                        onTap: (){
                                          SmartDialog.dismiss();
                                          dwList = [{'name':'每吨/价格','id':'2'}];
                                          dwStr = '';
                                          for (var element in dwList) {
                                            dwStr += element['name'];
                                          }
                                          pageNum=1;
                                          getXianHuo();
                                        },
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            SizedBox(width: 40.w,),
                                            Text('每吨/价格',style: TextStyle(
                                                color: dwStr=='每吨/价格'? Color(0xffEA6B2B):Colors.black,
                                                fontSize: 30.sp,
                                                fontWeight: FontWeight.w500
                                            ),),
                                            SizedBox(width: 10.w,),
                                            Icon(Icons.arrow_forward_ios,color:Colors.transparent,size: 30.sp,)
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),right: 15.w,top: 10.w,)
                            ],
                          ),
                        ),
                      ),
                    ))
                  ],
                ),
              );
          },
          );
          // for (var element in dwList) {
          //   selectIds.add(element['id']);
          // }
          return;
        }
        SmartDialog.show(
          alignment: Alignment.center,
          clickMaskDismiss: true,
          maskColor: Colors.transparent, builder: (BuildContext context) {
            return XianHuoSXLXPage(
              sxType: type,
              selectIds: selectIds,
              topSpace: renderBox.size.height+offset.dy,
              callBack: (list){
                if(list!=null){
                  setState(() {
                    if(type==0){
                      plList = list;
                      plStr = '';
                      for (var element in plList) {
                        plStr += element['name'];
                      }
                    }else if(type==1){
                      lxList = list;
                      lxStr = '';
                      for (var element in lxList) {
                        lxStr += element['name'];
                      }
                    }else if(type==2){
                      dwList = list;
                      dwStr = '';
                      for (var element in dwList) {
                        dwStr += element['name'];
                      }
                    }
                  });
                }
                pageNum=1;
                getXianHuo();
              },
            );
        },);
      },
      child: Container(
        child: Row(
          children: [
            Text(name.length>5?name.substring(0,5):name,style: TextStyle(
                color: color,
                fontSize: 26.sp
            ),maxLines: 1,),
            Visibility(child: icon ?? Container()),
          ],
        ),
      ),
    );
  }

}
